//
//  RWTSwap.m
//  CandyCrushClone
//
//  Created by  Stefan Nestorov on 12/29/14.
//  Copyright (c) 2014 Nestorov Engineering. All rights reserved.
//

#import "RWTSwap.h"
#import "RWTCookie.h"
#import "Globals.h"
#import "RWTLevel.h"

@implementation RWTSwap

+(instancetype)createSwapObjectFromSFSObject:(SFSObject *)sfsSwapObject
{
    
    // get SFSCookieObject
    SFSObject *sfsCookieA = [sfsSwapObject getSFSObject:SWAP_COOKIE_A];
    SFSObject *sfsCookieB = [sfsSwapObject getSFSObject:SWAP_COOKIE_B];
    
    NSInteger colA = [sfsCookieA getInt:COLUMN];
    NSInteger rowA = [sfsCookieA getInt:ROW];
    
    NSInteger colB = [sfsCookieB getInt:COLUMN];
    NSInteger rowB = [sfsCookieB getInt:ROW];
    
    // get RWTCookie from SFSCookieObject
    RWTCookie *cookieA = [[LevelAdapter sharedAdapter].delegate cookieAtColumn:colA row:rowA]; //[RWTCookie createCookieFromSFSObect:sfsCookieA];
    RWTCookie *cookieB = [[LevelAdapter sharedAdapter].delegate cookieAtColumn:colB row:rowB]; // [RWTCookie createCookieFromSFSObect:sfsCookieB];
    
    RWTSwap *swap = [[RWTSwap alloc] init];
    swap.cookieA = cookieA;
    swap.cookieB = cookieB;
    
    return swap;
    
}

- (NSString *)description
{
    
    return [NSString stringWithFormat:@"%@ swap %@ with %@",
            [super description],
            self.cookieA,
            self.cookieB
            ];

}

- (BOOL)isEqual:(id)object
{
    
    // You can only compare this object against other RWTSwap objects.
    if (![object isKindOfClass:[RWTSwap class]]) return NO;
    
    // Two swaps are equal if they contain the same cookie, but it doesn't
    // matter whether they're called A in one and B in the other.
    RWTSwap *other = (RWTSwap *)object;
    
    return ([other.cookieA isEqual:self.cookieA] && [other.cookieB isEqual:self.cookieB]) ||
    ([other.cookieB isEqual:self.cookieA] && [other.cookieA isEqual:self.cookieB]);
    
}

- (NSUInteger)hash {
    
    return [self.cookieA hash] ^ [self.cookieB hash];
    
}


- (SFSObject *)asSFSObject
{

    SFSObject *swapSFSObj = [SFSObject new];
    [swapSFSObj putSFSObject:SWAP_COOKIE_A value:[_cookieA asSFSObject]];
    [swapSFSObj putSFSObject:SWAP_COOKIE_B value:[_cookieB asSFSObject]];
    
    return swapSFSObj;
    
}


@end
